﻿@model Entity.NumberingRule
@using Microsoft.AspNetCore.Mvc.Rendering
@{
    // 从首页URL参数获取目标表单数据，或使用Model值
    var targetFormText = Context.Request.Query["targetForm"].FirstOrDefault() ?? Model.TargetForm ?? "";
    var targetFormValue = Context.Request.Query["targetFormValue"].FirstOrDefault() ?? Model.TargetID.ToString() ?? "";
}

<!-- 编辑表单：无action，通过JS提交 -->
<form id="editRuleForm">
    <!-- 隐藏字段：核心数据传递 -->
    <input type="hidden" name="RuleID" value="@Model.RuleID">
    <input type="hidden" name="TargetID" value="@targetFormValue"> <!-- 传递目标表单ID给后端 -->
    <!-- 1. 目标表单：可编辑文本框，从首页获取初始值 -->
    <div class="row mb-3">
        <label for="TargetForm" class="col-sm-3 col-form-label text-nowrap">目标表单 <span class="text-danger">*</span></label>
        <div class="col-sm-9">
            <input type="text" class="form-control"
                   id="TargetForm"
                   name="TargetForm"
                   value="@targetFormText"
                   placeholder="例如：货品信息"
                   required>
            <div class="form-text text-muted mt-1">该值从首页当前记录带入，可直接修改</div>
        </div>
    </div>

    <!-- 2. 编号前缀 -->
    <div class="row mb-3">
        <label for="NumberPrefix" class="col-sm-3 col-form-label text-nowrap">编号前缀 <span class="text-danger">*</span></label>
        <div class="col-sm-9">
            <input type="text" class="form-control" id="NumberPrefix" name="NumberPrefix"
                   value="@Model.NumberPrefix" placeholder="例如：HP" required>
        </div>
    </div>

    <!-- 3. 时间规则（复选框） -->
    <div class="row mb-3">
        <label class="col-sm-3 col-form-label">时间规则 <span class="text-danger">*</span></label>
        <div class="col-sm-9 d-flex flex-wrap gap-3 align-items-center">
            <div class="form-check">
                <input class="form-check-input" type="checkbox" id="IncludeYear" name="IncludeYear"
                @(Model.IncludeYear ? "checked" : "")>
                <label class="form-check-label" for="IncludeYear">年(YYYY)</label>
            </div>
            <div class="form-check">
                <input class="form-check-input" type="checkbox" id="IncludeMonth" name="IncludeMonth"
                @(Model.IncludeMonth ? "checked" : "")>
                <label class="form-check-label" for="IncludeMonth">月(MM)</label>
            </div>
            <div class="form-check">
                <input class="form-check-input" type="checkbox" id="IncludeDay" name="IncludeDay"
                @(Model.IncludeDay ? "checked" : "")>
                <label class="form-check-label" for="IncludeDay">日(DD)</label>
            </div>
            <div class="form-check">
                <input class="form-check-input" type="checkbox" id="IncludeHour" name="IncludeHour"
                @(Model.IncludeHour ? "checked" : "")>
                <label class="form-check-label" for="IncludeHour">时(HH)</label>
            </div>
            <div class="form-check">
                <input class="form-check-input" type="checkbox" id="IncludeMinute" name="IncludeMinute"
                @(Model.IncludeMinute ? "checked" : "")>
                <label class="form-check-label" for="IncludeMinute">分(mm)</label>
            </div>
            <div class="form-check">
                <input class="form-check-input" type="checkbox" id="IncludeSecond" name="IncludeSecond"
                @(Model.IncludeSecond ? "checked" : "")>
                <label class="form-check-label" for="IncludeSecond">秒(ss)</label>
            </div>
            <!-- 自定义验证：确保至少选择一个时间规则 -->
            <div class="w-100 invalid-feedback d-none" id="timeRuleError">请至少选择一个时间规则</div>
        </div>
    </div>

    <!-- 4. 流水号位数 -->
    <div class="row mb-3">
        <label for="SerialNumber" class="col-sm-3 col-form-label text-nowrap">流水号位数 <span class="text-danger">*</span></label>
        <div class="col-sm-9">
            <input type="number" class="form-control" id="SerialNumber" name="SerialNumber"
                   value="@(Model.SerialNumber > 0 ? Model.SerialNumber : 3)"
                   min="1" max="10"
                   placeholder="例如：3（生成001、002...）"
                   required>
        </div>
    </div>

    <!-- 5. 步长 -->
    <div class="row mb-3">
        <label for="Step" class="col-sm-3 col-form-label text-nowrap">步长 <span class="text-danger">*</span></label>
        <div class="col-sm-9">
            <input type="number" class="form-control" id="Step" name="Step"
                   value="@(Model.Step > 0 ? Model.Step : 1)"
                   min="1"
                   placeholder="例如：1（每次递增1）"
                   required>
        </div>
    </div>

    <!-- 6. 规则预览（只读，实时更新） -->
    <div class="row mb-3">
        <label for="NumberProductionRule" class="col-sm-3 col-form-label">规则预览</label>
        <div class="col-sm-9">
            <input type="text" class="form-control" id="NumberProductionRule" name="NumberProductionRule"
                   value="@Model.NumberProductionRule"
                   readonly
                   style="background-color: #fff; border-color: #dee2e6;">
            <div class="form-text text-muted mt-1">示例：[货品信息]HP20240520001（前缀+时间+流水号）</div>
        </div>
    </div>

    <!-- 7. 操作按钮 -->
    <div class="row mt-4">
        <div class="col-sm-9 offset-sm-3 d-flex gap-2">
            <button type="button" class="btn btn-primary" onclick="saveRule()">保存</button>
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        </div>
    </div>
</form>

<script>
    $(function () {
        // 1. 初始化：加载时立即生成规则预览
        updateRulePreview();

        // 2. 绑定事件：监听可修改字段的变化，更新预览
        $("#NumberPrefix, #SerialNumber, #Step, #TargetForm").on("input", updateRulePreview);
        $("input[name^='Include']").on("change", updateRulePreview);
    });

    /**
     * 生成编号规则预览（包含目标表单名称前缀）
     */
    function updateRulePreview() {
        // 基础数据获取
        const prefix = $("#NumberPrefix").val() || "";
        const targetFormText = $("#TargetForm").val() || "";
        const serialLen = parseInt($("#SerialNumber").val()) || 3;
        let timePart = "";

        // 1. 拼接目标表单前缀
        const targetFormPart = targetFormText ? `[${targetFormText}]` : "";

        // 2. 拼接时间部分（根据复选框选择）
        if ($("#IncludeYear").is(":checked")) timePart += "YYYY";
        if ($("#IncludeMonth").is(":checked")) timePart += "MM";
        if ($("#IncludeDay").is(":checked")) timePart += "DD";
        if ($("#IncludeHour").is(":checked")) timePart += "HH";
        if ($("#IncludeMinute").is(":checked")) timePart += "mm";
        if ($("#IncludeSecond").is(":checked")) timePart += "ss";

        // 3. 拼接流水号部分（补0处理）
        const serialPart = Array(serialLen + 1).join("0");

        // 4. 拼接完整预览
        const fullPreview = `${targetFormPart}${prefix}${timePart}${serialPart}`;
        $("#NumberProductionRule").val(fullPreview);
    }

    /**
     * 保存规则（带验证和加载状态）
     */
    function saveRule() {
        const form = $("#editRuleForm");
        const timeRuleCheckeds = $("input[name^='Include']:checked").length;
        let isValidatePass = true;

        // 1. 基础HTML5验证
        if (!form[0].checkValidity()) {
            form[0].reportValidity();
            return;
        }

        // 2. 自定义验证：时间规则至少选一个
        if (timeRuleCheckeds === 0) {
            $("#timeRuleError").removeClass("d-none");
            isValidatePass = false;
        } else {
            $("#timeRuleError").addClass("d-none");
        }

        // 3. 验证不通过则终止
        if (!isValidatePass) {
            return;
        }

        // 4. 收集表单数据
        const formData = form.serialize();

        // 5. AJAX提交
        const saveBtn = $("button:contains('保存')").prop("disabled", true).text("保存中...");
        $.post("/NumberingRule/Save", formData)
            .done(function (res) {
                if (res.success) {
                    alert("保存成功！规则将立即生效~");
                    // 关闭模态框+刷新首页表格
                    const modal = bootstrap.Modal.getInstance(document.getElementById("editModal"));
                    modal.hide();
                    if (parent && typeof parent.refreshTable === "function") {
                        parent.refreshTable();
                    }
                } else {
                    alert(`保存失败：${res.message || '未知错误，请重试'}`);
                }
            })
            .fail(function (xhr) {
                alert(`请求错误：${xhr.responseText || '网络异常，请检查连接'}`);
            })
            .always(function () {
                // 恢复按钮状态
                saveBtn.prop("disabled", false).text("保存");
            });
    }
</script>
